package com.gitee.taotaojs.myboot.service;

import com.gitee.taotaojs.myboot.bean.DemoBean;
import com.gitee.taotaojs.myboot.mapper.DemoMapper;
import com.gitee.taotaojs.mybootsuper.service.MyComService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author TaoTaojs
 * @date 2019/3/13 23:35
 * <p>Description</p>
 * 测试类Service
 * 关联类:
 * 参考链接：
 */
@Service
public class DemoService extends MyComService<DemoBean> {

    @Autowired
    private DemoMapper mapper;

    private volatile int index = 0;

    public List<DemoBean> getList() {
        return mapper.selectAll();
    }

    public List<DemoBean> getListById(Integer id) {
        DemoBean demoBean = new DemoBean();
        demoBean.setId(id);
        return mapper.select(demoBean);
    }

    /**
     * 与Mapper文件的兼容测试方法
     * @return 测试
     */
    public Integer getStatistics() {
        return mapper.getStatistics();
    }

    /**
     * 地方
     */
    public void addDB() {
        mapper.updateBySql("update tb_demo set status = status-1 where id = 8");
    }

    @SuppressWarnings("ALL")
    public void demo() {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 500, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
//                        orgTree.put(r);
                        System.out.println("线程"+r.hashCode()+"创建");
                        //线程命名
                        Thread th = new Thread(r,"threadPool"+r.hashCode());
                        return th;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()) {

            @Override
            protected void beforeExecute(Thread t,Runnable r) {
//                System.out.println("准备执行：" + r.toString() + r.hashCode());
            }

            @Override
            protected void afterExecute(Runnable r,Throwable t) {
//                System.out.println("执行完毕：" + r.toString() + r.hashCode());
                System.out.println(++index);
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }
        };

        for(int i=0;i<1000;i++) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        addDB();
                    }
                }
            });
        }
    }

}
